package main.leetcode.offer.secondround.from03to50;

import main.datastruc.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/** 32-III.从上到下打印二叉树 */
public class ex32III {
    public static void main(String[] args) {
        TreeNode root = TreeNode.creCmpBTree(new int[] {3, 9, 20, 1, 1, 15, 7});
        System.out.println(new ex32III().levelOrder(root));
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        TreeNode node;
        LinkedList<Integer> list;
        int level = 0;
        while (!queue.isEmpty()) {
            list = new LinkedList<>();
            int n = queue.size();
            for (int i = 0; i < n; ++i) {
                node = queue.poll();
                if ((level & 1) == 1) {
                    list.addFirst(node.val);
                } else {
                    list.addLast(node.val);
                }
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            ++level;
            res.add(list);
        }
        return res;
    }
}
